package com.gc.service;

import com.gc.pojo.Article;
import com.gc.pojo.Page;
import com.gc.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;


@Service
public class ArticleService {


    @Autowired
    private ArticleRepository articleRepository;

    public Page<Article> findAll(int page, int size) {
        //查询出总记录数
        long count = articleRepository.count();
        if (page < 0) {
            page = 0;
        }
        //查询出分页结果
        PageRequest pageRequest = PageRequest.of(page, size);
        org.springframework.data.domain.Page<Article> all = articleRepository.findAll(pageRequest);
        //总页码
        long pageTotal = count / size;
        //如果有余数 总页码加1
        if (count%size!=0){
            pageTotal++;
        }
        //将结果封装到自己定义的page类中
        Page<Article> articlePage = new Page<>();
        articlePage.setPage(page);
        articlePage.setSize(size);
        articlePage.setTotal(count);
        articlePage.setPageList(all.getContent());
        articlePage.setPageTotal(pageTotal);
        return articlePage;
    }
}
